import base64
import os
import pickle
from audioop import reverse
from collections import OrderedDict

from django.http import HttpResponse
from django.shortcuts import render, redirect, render_to_response
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import GoodsChannel, SKU
from apps.index.models import ContentCategory


class IndexView(View):
    def get(self, request):
        """
        主页
        :param request:
        :return:
        """
        # 查询商品频道和分类
        categories_dict = OrderedDict()  # 创建一个有序的字典（先添加的key-value在前面）
        channels = GoodsChannel.objects.order_by('group_id', 'sequence')
        for channel in channels:  # 总共是11个频道，每个频道中 基本上有3、4个商品类别
            group_id = channel.group_id  # 当前频道的id
            if group_id not in categories_dict:
                categories_dict[group_id] = {'channels': [], 'sub_cats': []}
            # 此时字典的样子为
            # {
            #     "1": {
            #         "channels": [],
            #         "sub_cats": []
            #     },
            # }

            category_1 = channel.category  # 当前频道的 商品类别（1级分类）

            # 追加1级分类信息到当前频道
            categories_dict[group_id]['channels'].append({
                'id': category_1.id,
                'name': category_1.name,
                'url': channel.url
            })
            # 此时字典的样子为
            # {
            #     "1": {
            #         "channels": [
            #             {"id": 1, "name": "手机", "url": "http://shouji.jd.com/"},
            #             {"id": 2, "name": "相机", "url": "http://www.baidu.cn/"},
            #             {"id": 3, "name": "数码", "url": "http://www.baidu.cn/"},
            #         ],
            #         "sub_cats": []
            #     },
            # }

            # 构建当前类别的子类别（2、3级分类）
            for category_2 in category_1.subs.all():
                # 将2级分类模型类对象中的信息，转换为字典
                category_2_dict = {"id": category_2.id, "name": category_2.name, "sub_cats": []}
                for category_3 in category_2.subs.all():
                    # 将3级分类模型类对象中的信息，转换为字典
                    category_3_dict = {"id": category_3.id, "name": category_3.name}
                    category_2_dict["sub_cats"].append(category_3_dict)
                categories_dict[group_id]['sub_cats'].append(category_2_dict)

            # 此时字典的样子为
            # {
            #     "1": {
            #         "channels": [
            #             {"id": 1, "name": "手机", "url": "http://shouji.jd.com/"},
            #             {"id": 2, "name": "相机", "url": "http://www.baidu.cn/"},
            #             {"id": 3, "name": "数码", "url": "http://www.baidu.cn/"},
            #         ],
            #         "sub_cats": [
            #             {
            #                 "id": 38,
            #                 "name": "手机通讯",
            #                 "sub_cats": [
            #                     {"id": 115, "name": "手机"},
            #                     {"id": 116, "name": "游戏手机"}
            #                 ]
            #             },
            #             {
            #                 "id": 39,
            #                 "name": "手机配件",
            #                 "sub_cats": [
            #                     {"id": 119, "name": "手机壳"},
            #                     {"id": 120, "name": "贴膜"}
            #                 ]
            #             }
            #         ]
            #     },
            # }

        # 广告数据
        contents = {}
        content_categories = ContentCategory.objects.all()
        for temp in content_categories:
            contents[temp.key] = temp.content_set.filter(status=True).order_by('sequence')
        # 渲染模板的上下文
        # 判断用户是否登录
        user = request.user
        print(user)
        if user.is_authenticated:
            # 用户已登录，查询Redis购物车
            redis_conn = get_redis_connection('carts')
            redis_cart = redis_conn.hgetall('carts_%s' % user.id)
            cart_selected = redis_conn.smembers('selected_%s' % user.id)
            # 将redis中的两个数据统一格式，跟cookie中的格式一致，方便统一查询
            cart_dict = {}
            for sku_id, count in redis_cart.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in cart_selected
                }
        else:
            # 用户未登录，查询cookie购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

        # 构造简单购物车JSON数据
        cart_skus = []
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'count': cart_dict.get(sku.id).get('count'),
                'default_image_url': sku.default_image
            })
        print(cart_skus)
        # print(len(cart_skus))
        num = 0
        num2 = 0
        num3 = list()
        for c in cart_skus:
            # print(c["count"])
            # print(c['price'])
            num1 = c['count']
            price = c['price'] * num1
            num += num1
            num3.append(num1)
            num2 += price
        # print(num)
        # print(num2)
        print(num3)
        context = {
            'categories': categories_dict,
            'contents': contents,
            'cart_skus': cart_skus,
            'count': num,
            'price_mall': num2,
            'num3': num3,

        }

        return render(request, 'index.html', context=context)




